1. Static Assignment
You can directly assign values at the time of declaration.
#include < stdio.h>
int main() {
// Declare and initialize an array
int arr[5] = {10, 20, 30, 40, 50};
// Print values
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
2. Dynamic Assignment
You can assign values to specific elements after declaring the array.
#include < stdio.h>
int main() {
int arr[5]; // Declare an array
// Assign values to the array
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
arr[3] = 20;
arr[4] = 25;
// Print values
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
3. User Input to Array
You can take input from the user and assign values to an array.
#include < stdio.h>
int main() {
int arr[5]; // Declare an array
// Input values from the user
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5; i++) {
printf("Enter value for arr[%d]: ", i);
scanf("%d", &arr[i]); // Assign values based on user input
}
// Print the values
printf("\nThe values in the array are:\n");
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
4. Partially Initialized Arrays
If you initialize only some elements, the rest will automatically be set to 0.
#include < stdio.h>
int main() {
int arr[5] = {1, 2}; // Only the first two elements are initialized
// Print values to check
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
Key Points to Remember
- Indexing starts at 0: The first element is arr[0], the second is arr[1], and so on.
- Array size must be specified: When declaring an array without initializing it, you need to provide its size (e.g., int arr[10];).
- Out-of-bounds access: Accessing or modifying indices outside the array's declared size leads to undefined behavior.